package com.example.za.account.fragment;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.example.za.account.R;
import com.example.za.account.activity.AboutActivity;
import com.example.za.account.activity.LoginActivity;
import com.example.za.account.activity.MainActivity;
import com.example.za.account.activity.UserActivity;
import com.example.za.account.application.AccountApplication;
import com.example.za.account.model.User;
import com.example.za.account.receiver.AlarmReceiver;
import com.example.za.account.utils.Constant;
import com.example.za.account.utils.DBOpenHelper;
import com.example.za.account.utils.DateUtils;
import com.example.za.account.utils.L;
import com.example.za.account.utils.T;
import com.example.za.account.view.CircleImageView;

import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;

public class MineFragment extends BaseFragment {

    @BindView(R.id.iv_user_photo)
    CircleImageView ivUserPhoto;
    @BindView(R.id.me_username)
    TextView meUsername;
    Unbinder unbinder;
    private View rootView;
    private MainActivity mContext;
    private static final int UPDATE_USER = 1001;
    private BmobUser user;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = (MainActivity) getActivity();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = super.onCreateView(inflater, container, savedInstanceState);
            unbinder = ButterKnife.bind(this, rootView);
            user = BmobUser.getCurrentUser(User.class);
            User user1 = (User) user;
            File file = new File(mContext.getExternalFilesDir(null) + File.separator + BmobUser.getCurrentUser(User.class).getObjectId()
                    + File.separator + user1.getmPicture());
            if (file.exists()) {
                ivUserPhoto.setImageBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()));
            }
            meUsername.setText(user.getUsername());

        }
        // 缓存的rootView需要判断是否已经被加过parent，如果有parent需要从parent删除，
        // 要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }

        return rootView;
    }

    @Override
    protected Fragment getSubFragment() {
        return this;
    }

    @Override
    protected int getResId() {
        return R.layout.fragment_mine;
    }

    @OnClick({R.id.ll_me_user, R.id.ll_me_reminder, R.id.ll_me_check, R.id.ll_me_about, R.id.ll_me_init})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_me_user:
                startActivityForResult(new Intent(mContext, UserActivity.class), UPDATE_USER);
                break;
            case R.id.ll_me_reminder:
                //时间选择器
                TimePickerView pvTime = new TimePickerView.Builder(getActivity()
                        , new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        //   tvTime.setText(getTime(date));
                        Intent intent = new Intent(mContext, AlarmReceiver.class);
                        intent.setAction(Constant.ACTION_ALARM);
                        PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0,
                                intent, PendingIntent.FLAG_UPDATE_CURRENT);
                        AlarmManager am = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
                        am.set(AlarmManager.RTC_WAKEUP, date.getTime(), pendingIntent);
                        T.showShort(mContext, "闹钟将在" + DateUtils.date2Str(date, "MM-dd HH:mm")
                                + "发出提醒");

                    }
                }).build();
                pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                pvTime.show();

                break;
            case R.id.ll_me_check:
                final ProgressDialog dialog = new ProgressDialog(mContext);
                dialog.setTitle("正在检测新版本");
                dialog.setMessage("请稍后...");
                dialog.setCancelable(false);
                dialog.setIndeterminate(true);
                dialog.getWindow().setBackgroundDrawableResource(R.drawable.alert_background);


                dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        T.showShort(mContext, "已是最新版本，无需更新！");
                    }
                });
                dialog.show();
                TimerTask task = new TimerTask() {
                    @Override
                    public void run() {
                        dialog.cancel();
                    }
                };
                Timer timer = new Timer();
                timer.schedule(task, Constant.DELAY_TIME);

                break;
            case R.id.ll_me_about:
                startActivity(new Intent(mContext, AboutActivity.class));
                break;
            case R.id.ll_me_init:
                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                builder.setTitle("警告");
                builder.setCancelable(true);
                builder.setMessage(" 初始化将删除所有的软件记录并恢复软件的最初设置，你确定这么做吗？");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //在这里初始化所有数据表，并退出登录
                        DBOpenHelper.getInstance(mContext).dropTable();
                        BmobUser.logOut();
                        AccountApplication.sUser = null;
                        startActivity(new Intent(mContext, LoginActivity.class));
                        mContext.finish();
                    }
                });
                builder.setNegativeButton("取消", null);
                builder.show();
                break;
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK && requestCode == UPDATE_USER) {
            String newName = data.getStringExtra(Constant.NEW_USERNAME);
            if (newName != null) {
                meUsername.setText(newName);
            }
            String newFile = data.getStringExtra(Constant.NEW_FILENAME);
            if (newFile != null) {
                File file = new File(mContext.getExternalFilesDir(null) + File.separator + BmobUser.getCurrentUser(User.class).getObjectId()
                        + File.separator + newFile);
                ivUserPhoto.setImageBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()));
            }
        }
    }

}
